<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      row-key="roleId"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer(t('accessControl.roleManagement.add'))">{{
          t("accessControl.roleManagement.addRole")
        }}</el-button>
        <el-button v-auth="'import'" type="primary" :icon="Upload" plain @click="batchAdd">{{
          t("accessControl.roleManagement.batchAddRoles")
        }}</el-button>
        <el-button v-auth="'export'" type="primary" :icon="Download" plain @click="downloadFile">{{
          t("accessControl.roleManagement.exportRoleData")
        }}</el-button>
        <el-button v-auth="'RLRL'" type="primary" plain @click="authSetting(scope.selectedList)">{{
          t("accessControl.roleManagement.setPermission")
        }}</el-button>
        <el-button
          v-auth="'delete'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedList)"
        >
          {{ t("accessControl.roleManagement.deleteRole") }}
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success(t('accessControl.roleManagement.headerRenderSuccess'))">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success(t('accessControl.roleManagement.contentRenderSuccess'))">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" v-auth="'RLRL'" link :icon="Avatar" @click="settingRoleAuth(scope.row)">{{
          t("accessControl.roleManagement.setPermission")
        }}</el-button>
        <el-button
          type="primary"
          v-auth="'edit'"
          link
          :icon="EditPen"
          @click="openDrawer(t('accessControl.roleManagement.edit'), scope.row)"
        >
          {{ t("accessControl.roleManagement.editRole") }}
        </el-button>
        <el-button type="primary" v-auth="'delete'" link :icon="Delete" @click="deleteAccount(scope.row)">{{
          t("accessControl.roleManagement.deleteRole")
        }}</el-button>
      </template>
    </ProTable>
    <TreeFilter2 ref="authRef" @send-data="sendDataAddFrom" />
    <!-- 	<el-dialog title="权限批量设置" v-model="dialogTableVisible"  >
		<div :style="{'height':'500px'}">
			
		</div>
		</el-dialog> -->
    <!-- <TreeFilter2 @send-data="sendData" /> -->
    <!-- <div> <el-row type="flex" class="row-bg" justify="center">
    <el-col :span="12" class="div-half">左半部分</el-col>
    <el-col :span="12" class="div-half">右半部分</el-col>
  </el-row></div> -->

    <UserDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { User, RoleManager } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/accessControl/roleManagement/components/RoleDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import {
  getUserList,
  deleteUser,
  editUser,
  addUser,
  changeUserStatus,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser
} from "@/api/modules/user";

import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";

const { t } = useI18n();
const router = useRouter();
// const dialogTableVisible = ref(false);
// 跳转详情页
const toDetail = () => {
  router.push(`/proTable/useProTable/detail/${Math.random().toFixed(3)}?params=detail-page`);
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const settingAuthRoleIds = ref("");
//子组件弹窗回调方法
const sendDataAddFrom = (data: any) => {
  setResourceByRoleIds(data + "-" + settingAuthRoleIds.value).then(res => {
    if (res.toString() == "true") {
      ElMessage.success("权限设置成功");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    } else {
      ElMessage.error("权限设置失败");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    }
  });
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "roleId";
  newParams.sord = "desc";
  delete newParams.pageNum;
  delete newParams.pageSize;
  return roleFind(newParams, "roleQueryDto", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success(t("accessControl.roleManagement.headerRenderSuccess"))}>
      {scope.column.label}
    </el-button>
  );
};

// 表格配置项
const columns = reactive<ColumnProps<RoleManager.ResRoleList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "roleName", label: t("accessControl.roleManagement.roleName"), search: { el: "input" }, sortable: true },
  { prop: "roleCode", label: t("accessControl.roleManagement.roleCode"), search: { el: "input" }, sortable: true },
  { prop: "description", label: t("accessControl.roleManagement.description"), search: { el: "input" }, sortable: true },
  { prop: "remark", label: t("accessControl.roleManagement.remark"), search: { el: "input" }, sortable: true },
  {
    prop: "roleState",
    label: t("accessControl.roleManagement.status"),
    width: 110,
    render: scope => (
      <>{scope.row.roleState === true ? t("accessControl.roleManagement.enabled") : t("accessControl.roleManagement.disabled")}</>
    )
  },
  { prop: "operation", label: t("accessControl.roleManagement.operation"), fixed: "right", width: 280 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success(t("accessControl.roleManagement.sortSuccess"));
};

// 设置角色权限
const settingRoleAuth = async (params: RoleManager.ResRoleList) => {
  settingAuthRoleIds.value = params.roleId.toString();
  authRef.value?.acceptParams(params.roleId.toString(), true);
  // proTable.value?.clearSelection();
  // proTable.value?.getTableList();
};

// 删除用户信息
const deleteAccount = async (params: RoleManager.ResRoleList) => {
  batchDelete([params]);
  //await useHandleData(deleteUser, { id: [params.id] }, `删除【${params.username}】用户`);
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 批量删除用户信息
const batchDelete = async (id: any[]) => {
  console.log(id);
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?ids=" + id[i].roleId;
    } else {
      idsStr = idsStr + "&ids=" + id[i].roleId;
    }
    NameStr = NameStr + id[i].roleName + ",";
  }
  ElMessageBox.confirm(
    t("accessControl.roleManagement.deleteConfirm", { names: NameStr }),
    t("accessControl.roleManagement.deleteConfirm"),
    {
      confirmButtonText: t("common.confirm"),
      cancelButtonText: t("common.cancel"),
      type: "warning",
      center: true
    }
  )
    .then(() => {
      console.log("sssssssssssaaaaaaaaaaa");
      console.log(idsStr);
      //await useHandleData(deleteUser, { id }, "删除所选用户信息");
      deleteRole(idsStr).then(res => {
        ElMessage({
          type: "success",
          message: t("accessControl.roleManagement.deleteSuccess")
        });
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: t("accessControl.roleManagement.cancelDelete")
      });
    });
  // deleteRole
  //  await useHandleData(deleteUser, { id }, "删除所选用户信息");
  //  proTable.value?.clearSelection();
  //  proTable.value?.getTableList();
};

// 重置用户密码
const resetPass = async (params: User.ResUserList) => {
  await useHandleData(
    resetUserPassWord,
    { id: params.id },
    t("accessControl.roleManagement.resetPasswordConfirm", { username: params.username })
  );
  proTable.value?.getTableList();
};

// 切换用户状态
const changeStatus = async (row: User.ResUserList) => {
  await useHandleData(
    changeUserStatus,
    { id: row.id, status: row.status == 1 ? 0 : 1 },
    t("accessControl.roleManagement.changeStatusConfirm", { username: row.username })
  );
  proTable.value?.getTableList();
};

// 导出用户列表
const downloadFile = async () => {
  ElMessageBox.confirm(t("accessControl.roleManagement.confirmExport"), t("accessControl.roleManagement.tips"), {
    type: "warning"
  }).then(() => useDownload(exportRole, t("accessControl.roleManagement.roleList"), proTable.value?.searchParam));
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: t("accessControl.roleManagement.role"),
    tempApi: tempRole,
    importApi: importRoleData,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};
const authRef = ref<InstanceType<typeof TreeFilter2> | null>(null);
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<RoleManager.ResRoleList> = {}) => {
  const params = {
    title,
    isView: title === t("accessControl.roleManagement.view"),
    row: { ...row },
    api:
      title === t("accessControl.roleManagement.add")
        ? addUser
        : title === t("accessControl.roleManagement.edit")
          ? editUser
          : editUser,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
  proTable.value?.clearSelection();
};

const authSetting = async (id: any[]) => {
  if (id.length == 0) {
    ElMessage.error("至少选择一行");
    return;
  } else if (id.length == 1) {
    settingAuthRoleIds.value = id[0].roleId;
    authRef.value?.acceptParams(id[0].roleId, true);
  } else {
    let str = "";
    id.forEach(function (element) {
      str += element.roleId + ",";
    });
    if (str.endsWith(",")) {
      str = str.substring(0, str.length - 1);
    }
    settingAuthRoleIds.value = str;
    authRef.value?.acceptParams(str, false);
  }
};
</script>
